package mid.array;

import java.util.Arrays;

public class q16 {

    public static void main(String[] args) {
        int[] array = {-1,2,1,-4};
        int target = 1;
        System.out.println(threeSumClosest(array, target));
    }


    public static int threeSumClosest(int[] nums, int target) {
        int result = Integer.MAX_VALUE;
        int closest = -1;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int l = i + 1;
            int r = nums.length - 1;

            while (l < r) {
                int sum = nums[i] + nums[l] + nums[r];
                if (sum == target) {
                    return target;
                } else if (sum < target) {
                    int abs = Math.abs(sum - target);
                    result = Math.min(abs, result);
                    closest = abs == result ? sum : closest;
                    l++;
                } else {
                    int abs = Math.abs(sum-target);
                    result = Math.min(abs, result);
                    closest = abs == result ? sum : closest;
                    r--;
                }

            }

        }

        return closest;
    }

}
